﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpAdbClient;
using System.Threading;
using System.IO;
using System.Diagnostics;
using DroidLord.Core;

namespace DroidLord
{
    public partial class SlaveViewer : UserControl
    {
        private Slavery.Slave slave=null;

        public string deviceSn = null;
        private Graphics graph;
        private Image curFrame = null;

        /// <summary>
        /// 是否显示checkbxo和设备名称的控件
        /// </summary>
        public Boolean isShowControl = false;
        /// <summary>
        /// 是否是主控窗口
        /// </summary>
        public Boolean isControlViewer = false;

        public MainForm mainForm = null;

        /// <summary>
        /// 是否是主控窗体
        /// </summary>
        public Boolean isTotalControl = false;


        private Point mDownPoint;
        private Point mUpPoint;
        private List<Point> mMovePointList = new List<Point>();

        public ScreenFormControl screenFormControl = null;

        // 上次轮训窗口状态时间
        private DateTime lastQuery;

        // 显示右键菜单
        public bool ShowMenu
        {
            get; set;
        }             
            = false;

        // 响应鼠标事件
        public bool ResponseClick
        {
            get;
            set;
        }
        public Slavery.Slave GetSlave()
        {
            return slave;
        }
        public SlaveViewer()
        {
            InitializeComponent();

            // 鼠标事件
            ResponseClick = true;
            this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseDown);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseMove);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseUp);
            this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.my_MouseWheel);

            // 默认大小
            this.Width = 150;
            this.Height = 300;

            // 轮训窗口状态， 被遮挡则断开连接
            var timer = new System.Threading.Timer((obj) =>
            {
                // 轮询间隔保持1秒
                if (DateTime.Now.Subtract(lastQuery).TotalMilliseconds > 1000)
                {
                    LayoutScrolled();
                }
            }, null, 0, 1000);
        }

        public void LayoutScrolled()
        {
            if (slave != null)
            {
                lastQuery = DateTime.Now;
                try
                {
                    var scRect = RectangleToScreen(ClientRectangle);
                    if (IsOnScreen(scRect))
                    {
                        // 滚动没有遮住
                        slave.ScreenService.Start();
                    }
                    else
                    {
                        slave.ScreenService.Stop();
                    }
                }catch(Exception eeee)
                {

                }
            }
        }

        // Return True if at least the percent specified of the rectangle is shown on the total screen area of all monitors, otherwise return False.
        public bool IsOnScreen(System.Drawing.Rectangle Rec, double MinPercentOnScreen = 0.001)
        {
            double PixelsVisible = 0;

            foreach (Screen scrn in Screen.AllScreens)
            {
                System.Drawing.Rectangle r = System.Drawing.Rectangle.Intersect(Rec, scrn.WorkingArea);
                // intersect rectangle with screen
                if (r.Width != 0 & r.Height != 0)
                {
                    PixelsVisible += (r.Width * r.Height);
                    // tally visible pixels
                }
            }
            return PixelsVisible >= (Rec.Width * Rec.Height) * MinPercentOnScreen;
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (curFrame != null)
            {
                lock (curFrame)
                {
                    lock (e.Graphics)
                    {
                        try
                        {
                            e.Graphics.DrawImage(curFrame,
                               new Rectangle(0, 0, Width, Height),
                               new Rectangle(0, 0, curFrame.Width, curFrame.Height), GraphicsUnit.Pixel);
                            if (isTotalControl)
                            {
                                if (Program.mainFrom.WindowState == FormWindowState.Maximized)
                                {
                                   // MessageBox.Show("" + Width + " " + Height);
                                }
                            }
                        }
                        catch 
                        {                        
                        }                        
                    }
                }
            }
        }
        public void Display(Slavery.Slave sl)
        {
            this.slave = sl;
            slave.ScreenService.FrameArrived += ScreenService_FrameArrived;
            graph = this.CreateGraphics();
        }

        /// <summary>
        /// 移除屏幕同屏帧率通知
        /// </summary>
        public void removeFrameArrived()
        {
            try
            {

                slave.ScreenService.FrameArrived -= ScreenService_FrameArrived;

            }catch(Exception eeee)
            {

            }
        }
        public void Display(DeviceData dev)
        {
            deviceSn = dev.Serial;
            graph = this.CreateGraphics();

            new Thread(() =>
            {
                slave = new Slavery.Slave(dev, 480, 800);
                slave.ScreenService.FrameArrived += ScreenService_FrameArrived;
                slave.ScreenService?.Start();

                // 加入设备管理器
                Program.Slaves.Add(new SlavedDevice() { Key = slave.Device.Serial, Object = slave });
            })
            { IsBackground = true }.Start();

            if (isShowControl)
            {
                checkBoxShowScreen.Visible = true;
                labelDeviceName.Visible = true;
                checkBoxShowScreen.Text = "";
                checkBoxShowScreen.SetBounds(this.Width - checkBoxShowScreen.Width, this.Height - checkBoxShowScreen.Height, checkBoxShowScreen.Width, checkBoxShowScreen.Height);
                labelDeviceName.Text =dev.Serial;
                labelDeviceName.BackColor = Color.Transparent;
                labelDeviceName.ForeColor = Color.Red;
                labelDeviceName.Parent = this;

                labelDeviceName.SetBounds(0+1,0+1, labelDeviceName.Width, labelDeviceName.Height);
                labelShowConnectStatus.SetBounds(0 + 1, this.Height / 2, this.Width - 10, this.Height - 10);
            }
            else
            {
                checkBoxShowScreen.Visible=false;
                labelDeviceName.Visible=false;
                setConnectStatusControlVisible(false);

            }
        }
        // 鼠标坐标映射到触屏坐标
        Point transTouch(int x, int y)
        {
            var wid = (double)Width;
            var hei = (double)Height;
            var dstX = x / wid;
            var dstY = y / hei;
            return new 
                Point(
                (int)(dstX * slave.ScreenService.Width), 
                (int)(dstY * slave.ScreenService.Height));
        }

        public string getDeviceSn()
        {
            return deviceSn+"";
        }


        private void MainForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (ResponseClick && e.Button == MouseButtons.Left)
            {
                down = true;
                mDownPoint = transTouch(e.X, e.Y);
                mMovePointList.Clear();
                if (!Program.isOpenTotalControl|| !isControlViewer)
                {
                    slave.Manipulation.TouchDown(transTouch(e.X, e.Y));
                }
                
            }
        }


        private void my_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
           // MessageBox.Show("滚动事件已被捕捉:"+e.Delta);
            if(e.Delta<0)
            {
                slave.Manipulation.buttonUp();
            }
            else
            {
                slave.Manipulation.buttonDown();
            }
        }


        private void MainForm_MouseUp(object sender, MouseEventArgs e)
        {
            if (ResponseClick&&e.Button==MouseButtons.Left)
            {
                down = false;
                mUpPoint = transTouch(e.X, e.Y);
                if (!Program.isOpenTotalControl || !isControlViewer)
                {

                    slave.Manipulation.TouchUp(transTouch(e.X, e.Y));
                }
                else
                {
                    //此处判断是点击还是swipe
                    if(mMovePointList.Count>5)
                    {
                        slave.Manipulation.inputSwipe(mDownPoint, mUpPoint);
                    }
                    else
                    {
                        slave.Manipulation.inputTap(mUpPoint);
                    }
                    foreach (var v in MainForm.mainForm.layoutPanel.Controls)
                    {
                        if (v is SlaveViewer)
                        {

                            var view = v as SlaveViewer;
                            if(!view.GetSlave().Device.Serial.Equals(slave.Device.Serial))
                            {
                                if (mMovePointList.Count > 5)
                                {
                                    view.GetSlave().Manipulation.inputSwipe(mDownPoint, mUpPoint);
                                }
                                else
                                {
                                    view.GetSlave().Manipulation.inputTap(mUpPoint);
                                }
                            }
                            
                        }
                    }

                }
            }
        
        }
        bool down = false;
        private void MainForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left
                && ResponseClick)
            {
                if (down)
                {
                    if (!Program.isOpenTotalControl||!isControlViewer)
                    {
                        slave.Manipulation.TouchMove(transTouch(e.X, e.Y));
                    }
                    else
                    {
                        mMovePointList.Add(transTouch(e.X, e.Y));
                    }
                }
                else
                {
                    if(screenFormControl!=null)
                    {
                        screenFormControl.panelControl_MouseMove(sender, e);
                    }
                    if(isTotalControl)
                    {
                        Program.mainFrom.panelControl_MouseMove(sender, e);
                    }
                }
                //var sc = Parent as Panel;
                //sc.ScreenForm_MouseMove(sender, e);
                try
                {
                    var sc = Parent as ScreenForm;
                    if (sc != null)
                    {
                        sc.ScreenForm_MouseMove(sender, e);
                    }
                }catch(Exception eeee)
                {

                }
            }
        }

        private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            slave.Manipulation.Keypress(e.KeyChar.ToString());
        }

        private bool ScreenService_FrameArrived(DeviceData device, object sender, Image frame)
        {
            if (this.Visible)
            {
                curFrame = frame;
                graph.DrawImage(frame,
                        new Rectangle(0, 0, Width, Height),
                        new Rectangle(0, 0, frame.Width, frame.Height), GraphicsUnit.Pixel);
                GC.Collect();
                return true;
            }
            else
            {
              //  MessageBox.Show("not visible");
            }
            return false;
        }

        private void 命令行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var adbPath = Program.usrDir + @"\bin\adb.exe";
            var serial = slave.Device.Serial;
            var proc = new Process()
            {               
                StartInfo = new ProcessStartInfo()
                {
                    FileName = adbPath,
                    Arguments = $"-s \"{serial}\" shell",
                    WindowStyle = ProcessWindowStyle.Normal                    
                }
            };           
            proc.Start();
        }

        private void SlaveViewer_MouseDown(object sender, MouseEventArgs e)
        {
            // 加载中...等待加载完毕
            if (slave == null)
            {
                MessageBox.Show("设备同屏初始化未完成,稍后再操作");
                return;
            }
            if (e.Button == MouseButtons.Right)
            {
                if (!ShowMenu)
                {
                    // 只显示按键选项
                    for(int i = 0; i < devMenu.Items.Count; i++)
                    {
                        if (devMenu.Items[i].Name.Contains("keys"))
                        {
                            break;
                        }
                        devMenu.Items[i].Visible = false;
                    }
                }
                devMenu.Items[0].Text = slave.Device.Serial;
                devMenu.Show(this, new Point(e.X, e.Y));                               
            }
        }

        private void 控制设备ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 加载中...等待加载完毕

            if (slave == null)
            {
                MessageBox.Show("设备同屏初始化未完成,稍后再操作");
                return;
            }
            var sla = slave;
            if (1 > 0)
            {
                if (1 > 0)
                {
                    var frm = new ScreenFormControl();
                    //frm.Width = 360;
                    //frm.Height = 720;
                    frm.StartPosition = FormStartPosition.CenterScreen;
                    frm.Display(sla);
                    frm.Show();
                    return;
                }
                else
                {
                    var frm = new ScreenForm();

                    frm.Width = 360;
                    frm.Height = 720;
                    frm.StartPosition = FormStartPosition.CenterScreen;
                    frm.Display(sla);
                    //frm.Parent = mainForm.controlPanel;
                    //mainForm.controlPanel.Controls.Add(frm);
                    //frm.ShowDialog();
                    frm.Show();
                }
            }
            else
            {

                mainForm.setMainControl(sla);
            }
        }

        private void 删除设备ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Program.Events.Raise(null, "adb_disconnect", slave.Device);
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            slave.Manipulation.Keypress(Slavery.DroidKey.HOME);

        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            slave.Manipulation.Keypress(Slavery.DroidKey.POWER);
            
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            slave.Manipulation.Keypress(Slavery.DroidKey.MENU);
        }

        private void 返回ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            slave.Manipulation.Keypress(Slavery.DroidKey.BACK);

        }

        private void 清除文本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            slave.Manipulation.ClearText();
            
        }

        private void 拷贝手机剪贴板ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            slave.Manipulation.pasteTextToPC();
        }

        private void checkBoxShowScreen_CheckedChanged(object sender, EventArgs e)
        {
             slave.isShowScreen = checkBoxShowScreen.Checked;
    }

        private void 切换到同屏输入法ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            slave.Manipulation.switchIme();
        }

        private void 我在哪儿ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            slave.Manipulation.findMe();
        }
        /// <summary>
        /// 设置连接状态的控件是否显示
        /// </summary>
        /// <param name="isVisible"></param>
        public  void setConnectStatusControlVisible(bool isVisible)
        {
            this.labelShowConnectStatus.Visible = isVisible;
        }


        public void  setConnectStatusText(String text)
        {
            this.labelShowConnectStatus.Text = text;
        }

        private void 设为主控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (slave == null)
            {
                MessageBox.Show("设备同屏初始化未完成,稍后再操作");
                return;
            }
            var sla = slave;
            if(2>1)
            {
                Program.mainFrom.createTotalControlView(sla);
                return;
            }
            if (1 > 0)
            {

                if(Program.totalControlViewer!=null)
                {
                    Program.totalControlViewer.removeFrameArrived();
                    Program.totalControlViewer = null;
                }
                var view = new SlaveViewer();
                
                view.isTotalControl = true;
                view.设为主控ToolStripMenuItem.Visible = false;
                view.setConnectStatusControlVisible(false);
                view.ResponseClick = true;
                
                view.Dock = DockStyle.Fill;
                view.screenFormControl = null;
                view.mainForm = Program.mainFrom;
                if (Program.mainFrom.WindowState == FormWindowState.Maximized)
                {
                    Program.mainFrom.panelControl.Width = 300;
                    Program.mainFrom.panelControl.Height = 600;
                }
                else
                {
                    Program.mainFrom.panelControl.Width = 240;
                    Program.mainFrom.panelControl.Height = 480;
                }
                Program.mainFrom.panelControl.Controls.Add(view);

                Program.mainFrom.panelControl.Parent = Program.mainFrom.controlPanel;
                //Program.mainFrom.panelControl.Width= Program.mainFrom.panelControl.Width-2;
                //Program.mainFrom.panelControl.Height = Program.mainFrom.panelControl.Height - 2;
                Program.mainFrom.panelControl.BringToFront();

                view.Left = Program.mainFrom.panelControl.Left;
                view.Top = Program.mainFrom.panelControl.Top;
                view.Width = Program.mainFrom.panelControl.Width;
                view.Height = Program.mainFrom.panelControl.Height;

                view.BringToFront();

                view.Display(sla);
                Program.mainFrom.alphaBlendTextBoxInputText.Parent = view;

                //Program.mainFrom.panelControl.Invalidate();
                view.BringToFront();
                view.Invalidate();

                Program.totalControlViewer = view;

                int mywidth = Program.mainFrom.controlPanel.Width;
                if (mywidth > Program.totalControlViewer.Width)
                {
                    int subWidth = mywidth - Program.totalControlViewer.Width;
                    int halfWidth = subWidth / 2;
                    Program.mainFrom.panelControl.SetBounds(Program.mainFrom.controlPanel.Location.X + halfWidth, Program.mainFrom.controlPanel.Location.Y + 1, Program.mainFrom.panelControl.Width, Program.mainFrom.panelControl.Height);
                }

                return;
            }
        }

        private void SlaveViewer_Load(object sender, EventArgs e)
        {

        }
    }
}
